//自定义 Promise 构造函数
function Promise(executor) {
  //为实例对象添加属性
  this.PromiseState = "pending";
  this.PromiseResult = undefined;
  this.callbacks = []; // 为实例对象添加属性

  let success = (value) => {
    //检测状态是否已经改变
    if (this.PromiseState !== "pending") return;
    //修改『状态』为成功, 设置成功的『结果值』
    this.PromiseState = "fulfilled";
    this.PromiseResult = value;
    //执行对应的回调
    this.callbacks.forEach((cbObj) => {
      //执行成功回调
      cbObj.ok(value);
    });
  };

  let fail = (reason) => {
    //检测状态是否已经改变
    if (this.PromiseState !== "pending") return;
    //修改『状态』为失败, 设置失败的『结果值』
    this.PromiseState = "rejected";
    this.PromiseResult = reason;
    this.callbacks.forEach((cbObj) => {
      //执行失败回调
      cbObj.ng(reason);
    });
  };

  try {
    //执行器函数是一个同步回调
    executor(success, fail);
  } catch (e) {
    //改变 promise 状态, 设置失败的结果值
    fail(e);
  }
}

//定义 then 方法
Promise.prototype.then = function (onFulfilled, onRejected) {
  //判断 onRejected 值     处理异常穿透
  if (typeof onRejected !== "function") {
    onRejected = (reason) => {
      throw reason;
    };
  }

  //判断 onFulfilled       处理值传递
  if (typeof onFulfilled !== "function") {
    onFulfilled = (value) => value;
  }

  return new Promise((resolve, reject) => {
    //封装函数 简化代码
    let callback = (type) => {
      setTimeout(() => {
        try {
          //获取回调函数的返回值
          let res = type(this.PromiseResult);

          //判断 res 是否为 promise 实例对象
          if (res instanceof Promise) {
            res.then(
              (v) => {
                resolve(v);
              },
              (r) => {
                reject(r);
              }
            );
          } else {
            //返回值不是 promise 的情况
            resolve(res);
          }
        } catch (e) {
          reject(e);
        }
      });
    };

    //判断 promise 实例对象的状态, 执行对应的回调函数
    if (this.PromiseState === "fulfilled") {
      callback(onFulfilled);
    }

    //失败的情况
    if (this.PromiseState === "rejected") {
      callback(onRejected);
    }

    //处理 pending 状态
    if (this.PromiseState === "pending") {
      //不能执行回调
      this.callbacks.push({
        ok: (value) => {
          callback(onFulfilled);
        },
        ng: (reason) => {
          callback(onRejected);
        },
      });
    }
  });
};

//添加 catch 方法
Promise.prototype.catch = function (onRejected) {
  return this.then(undefined, onRejected);
};

//定义 Promise.resolve
Promise.resolve = function (value) {
  return new Promise((resolve, reject) => {
    //判断 value
    if (value instanceof Promise) {
      value.then(
        (v) => {
          resolve(v);
        },
        (r) => {
          reject(r);
        }
      );
    } else {
      resolve(value);
    }
  });
};

//定义 Promise.reject
Promise.reject = function (reason) {
  return new Promise((resolve, reject) => {
    reject(reason);
  });
};

//定义 Promise.all
Promise.all = function (promiseArr) {
  //定义空数组 存放成功的结果值
  let resultArr = [];
  let counter = 0;
  return new Promise((resolve, reject) => {
    //遍历
    promiseArr.forEach((promise, index) => {
      //调用 then 方法
      promise.then(
        (v) => {
          resultArr[index] = v;
          counter++;
          //判断 resultArr 的长度
          if (counter === promiseArr.length) {
            resolve(resultArr);
          }
        },
        (r) => {
          reject(r);
        }
      );
    });
  });
};

//定义 Promise.race
Promise.race = function (promiseArr) {
  return new Promise((resolve, reject) => {
    promiseArr.forEach((promise) => {
      promise.then(
        (v) => {
          resolve(v);
        },
        (r) => {
          reject(r);
        }
      );
    });
  });
};
